<template>
  <el-dialog :title="form.id ? '基础信息' : '新增'" v-model="visible" :close-on-click-modal="false" draggable>
    <el-form ref="dataFormRef" :model="form" :rules="dataRules" formDialogRef label-width="90px"
             v-loading="loading">
      <el-row :gutter="20">
        <!--        <el-col :span="24" class="mb20">-->
        <!--          <el-form-item label="社保卡号" prop="medicalCard">-->
        <!--            <el-input v-model="form.medicalCard" placeholder="请输入社保卡号">-->
        <!--              <template #append>-->
        <!--                <el-button type="primary" @click="readCard">读卡</el-button>-->
        <!--              </template>-->
        <!--            </el-input>-->
        <!--          </el-form-item>-->
        <!--        </el-col>-->


        <el-col :span="12" class="mb20">
          <el-form-item label="姓名" prop="name">
            {{ form.name}}
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item label="身份证号" prop="icCard">
            {{ form.icCard}}
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item label="社保卡号" prop="medicalCard">
            {{ form.medicalCard}}
          </el-form-item>
        </el-col>


        <el-col :span="12" class="mb20">
          <el-form-item label="家庭医生" prop="doctorName">
            {{ form.doctorName}}
          </el-form-item>
        </el-col>




        <el-col :span="8" class="mb20">
          <el-form-item label="身高" prop="height">
            <el-input v-model="form.height" placeholder="请输入身高" @input="inputHeight">
              <template #append>cm</template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8" class="mb20">
          <el-form-item label="体重" prop="weight">
            <el-input v-model="form.weight" placeholder="请输入体重" @input="inputWeight">
              <template #append>kg</template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8" class="mb20">
          <el-form-item label="BMI数值" prop="bmi">
            <el-input v-model="form.bmi" placeholder="请输入BMI数值" disabled/>
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item label="收缩压" prop="systolicPressure">
            <el-input v-model="form.systolicPressure" placeholder="请输入收缩压">
              <template #append>mmHg</template>
            </el-input>
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item label="舒张压" prop="diastolicPressure">
            <el-input v-model="form.diastolicPressure" placeholder="请输入舒张压">
              <template #append>mmHg</template>
            </el-input>
          </el-form-item>
        </el-col>


      </el-row>
    </el-form>

    <template #footer>
			<span class="dialog-footer">
				<el-button @click="visible = false">取消</el-button>
				<el-button type="primary" @click="onSubmit" :disabled="loading">确认</el-button>
			</span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts" name="BloodxCustomerDialog">
// import {useDict} from '/@/hooks/dict';
import {useMessage} from '/@/hooks/message';
import {getObj, addObj, putObj, sysVillageList} from '/@/api/blood/bloodxCustomer';
import {rule} from '/@/utils/validate';
// import {readCardDevice} from '/@/utils/ajaxUtil';
// import {getDoctorList} from "/@/api/information/village";

const emit = defineEmits(['refresh']);

// 定义变量内容
const dataFormRef = ref();
const visible = ref(false);
const loading = ref(false);
const village = ref([]);
// 定义字典
// const {gender, bloodx_health, family_doctor} = useDict('gender', 'bloodx_health', 'family_doctor');

// const doctorList = ref<any[]>([]);
// 提交表单数据
const form = reactive({
  id: '',
  name: '',
  birthday: '',
  doctorName: '',
  // age: null,
  // sex: '',
  // examNum: '',
  icCard: '',
  // tel: '',
  // address: '',
  // village: '',
  localCard: '',
  // doctorName: '',
  medicalCard: '',
  // healthStatus: '0',
  // familyDoctor: '',
  height: null,
  weight: null,
  bmi: '',
  bloodPressure: '',
  diastolicPressure: '', // 舒张压
  systolicPressure: '', // 收缩压
});

// 定义校验规则
const dataRules = ref({
  // name: [{required: true, message: '请输入姓名', trigger: 'blur'}],
  // age: [{validator: rule.number, trigger: 'blur'}],
  height: [{required: true, trigger: 'blur', message: '请输入身高'}],
  weight: [{required: true, trigger: 'blur', message: '请输入体重'}],
  // tel: [{ validator: rule.mobilePhone, trigger: 'blur' }],
  // village: [{ required: true, message: '请选择村', trigger: 'blur' }],
});

const inputHeight = () => {
  if (form.weight) {
    form.bmi = (form.weight / ((form.height / 100) * (form.height / 100))).toFixed(2);
  }
};

const inputWeight = () => {
  if (form.height) {
    form.bmi = (form.weight / ((form.height / 100) * (form.height / 100))).toFixed(2);
  }
};

// 读卡
const readCard = async () => {
  loading.value = true;
  try {
    sendReadCard("ws://127.0.0.1:2018", (message) => {

      let list = JSON.parse(message).Data.kh.split("|")
      // console.log(list);
      form.name = list[4]
      form.medicalCard = list[1]
      form.icCard = list[1]
      form.localCard = list[2]
    });
    // const readRes = await sendReadCard();
    // if (readRes.code == 0) {
    // 	useMessage().success(readRes.msg);
    // 	form.name = '张三';
    // 	form.birthday = '1990-01-01';
    // 	form.age = 30;
    // 	form.medicalCard = readRes.data;
    // }
  } finally {
    loading.value = false;
  }
};
const sendReadCard = (WSURL, callback) => {
  let ws = new WebSocket(WSURL);
  ws.addEventListener("open", () => {
    // console.log("ws connected");
    ws.send("读卡");
  });

  ws.addEventListener("close", () => {
    // console.log("ws close");
  });

  ws.addEventListener("error", () => {
    ws.close();
    // console.log("ws error");
  });

  ws.addEventListener("message", (message) => {
    if (message.data !== "Open!") {
      callback(message.data);
      ws.close();
    }
  });
}
// const handleChangeVillage = (id: Object) => {
//   console.log(village.value)
//   form.familyDoctor = village.value.find((item) => item.id === id).doctorId;
//   form.doctorName = village.value.find((item) => item.id === id).doctorName;
// };

// const inputIcCard = (val: string) => {
// if (val.length === 18) {
// 	form.birthday = val.substring(6, 10) + '-' + val.substring(10, 12) + '-' + val.substring(12, 14);
// 	form.sex = parseInt(val.substring(16, 17)) % 2 === 0 ? '2' : '1';
// 	form.age = new Date().getFullYear() - parseInt(val.substring(6, 10));
// }
// };

// const getdoctorList = () => {
//   getDoctorList().then((res) => {
//     doctorList.value = res.data;
//   });
// };

// 打开弹窗
const openDialog = (id: string) => {
  visible.value = true;
  form.id = '';
  sysVillageList().then((res) => {
    village.value = res.data;
  });
  // 重置表单数据
  nextTick(() => {
    dataFormRef.value?.resetFields();
  });

  // 获取bloodxCustomer信息
  if (id) {
    form.id = id;
    getbloodxCustomerData(id);
  }

  // getdoctorList();
};

// 提交
const onSubmit = async () => {
  const valid = await dataFormRef.value.validate().catch(() => {
  });
  if (!valid) return false;

  try {
    loading.value = true;
    if (form.birthday && form.birthday.indexOf(':') === -1) {
      form.birthday += ' 00:00:00';
    }
    form.id ? await putObj(form) : await addObj(form);
    useMessage().success(form.id ? '修改成功' : '添加成功');
    visible.value = false;
    emit('refresh');
  } catch (err: any) {
    useMessage().error(err.msg);
  } finally {
    loading.value = false;
  }
};

// 初始化表单数据
const getbloodxCustomerData = (id: string) => {
  // 获取数据
  loading.value = true;
  getObj(id)
      .then((res: any) => {
        Object.assign(form, res.data);
      })
      .finally(() => {
        loading.value = false;
      });
};

// 暴露变量
defineExpose({
  openDialog,
});
</script>

<style scoped>
.radius {
  border: 1px solid var(--el-border-color);
  margin-top: 20px;
  border-radius: 4px;
}

.el-input-group__append button.el-button {
  border-top-left-radius: 0;
  border-bottom-left-radius: 0;
  border-color: var(--el-color-primary);
  background-color: var(--el-color-primary);
  color: var(--el-color-white);
}
</style>
